/*
 * @Author: rogi
 * @Date: 2022-07-19 17:10:27
 * @LastEditTime: 2022-07-19 17:16:22
 * @LastEditors: rogi
 * @Description: 描述
 */
import { mapState, mapGetters, createNamespacedHelpers, useStore } from 'vuex'
import { computed } from 'vue';

export function useMapper(mapper, mapFn) {
  const store = useStore()
  const storeDataFns = mapFn(mapper)
  const storeData = {}
  Object.keys(storeDataFns).forEach(fnKey => {
    const fn = storeDataFns[fnKey].bind({$store: store});
    storeData[fnKey] = computed(fn);
  })
  return storeData
}

export function useState(moduleName, mapper) {
  let mapperFn = mapState
  if (typeof moduleName === 'string' && moduleName.length > 0) {
    mapperFn = createNamespacedHelpers(moduleName).mapState
  } else {
    mapper = moduleName
  }
  return useMapper(mapper, mapperFn)
}

export function useGetters(moduleName, mapper) {
  let mapperFn = mapGetters
  if (typeof moduleName === 'string' && moduleName.length > 0) {
    mapperFn = createNamespacedHelpers(moduleName).mapGetters
  } else {
    mapper = moduleName
  }
  return useMapper(mapper, mapperFn)
}